<template>
	<view class="exam-records-page">
		<!-- 导航栏 -->
		<uv-navbar title="答题记录" :border="true" :fixed="true" placeholder>
			<template #left>
				<uv-icon name="arrow-left" size="20" @click="goBack"></uv-icon>
			</template>
		</uv-navbar>

		<!-- 搜索和筛选区域 -->
		<view class="search-filter-section">
			<view class="search-box">
				<uv-search 
					v-model="searchKeyword" 
					placeholder="搜索考试标题或昵称"
					@search="handleSearch"
					@clear="handleClear"
				></uv-search>
			</view>
			
			<view class="filter-tabs">
				<uv-tabs 
					:list="statusTabs" 
					:current="currentStatusTab"
					@change="handleStatusChange"
					lineWidth="30"
					lineColor="#007AFF"
				></uv-tabs>
			</view>
		</view>

		<!-- 记录列表 -->
		<view class="records-list">
			<view v-if="loading" class="loading-container">
				<uv-loading-icon mode="flower"></uv-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else-if="examRecords.length === 0" class="empty-container">
				<uv-empty mode="data" text="暂无答题记录"></uv-empty>
			</view>
			
			<view v-else class="records-container">
				<view 
					v-for="record in examRecords" 
					:key="record.userExamId"
					class="record-item"
					@click="viewRecordDetail(record)"
				>
					<view class="record-header">
						<view class="exam-title">{{ record.examTitle }}</view>
						<view class="status-badge" :class="getStatusClass(record.status)">
							{{ getStatusText(record.status) }}
						</view>
					</view>
					
					<view class="record-info">
						<view class="info-row">
							<text class="label">用户昵称：</text>
							<text class="value">{{ record.nickName }}</text>
						</view>
						<view class="info-row">
							<text class="label">开始时间：</text>
							<text class="value">{{ formatTime(record.startTime) }}</text>
						</view>
						<view class="info-row" v-if="record.submitTime">
							<text class="label">提交时间：</text>
							<text class="value">{{ formatTime(record.submitTime) }}</text>
						</view>
					</view>
					
					<view class="record-stats">
						<view class="stat-item">
							<text class="stat-label">得分</text>
							<text class="stat-value score">{{ record.score || 0 }}/{{ record.totalScore }}</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">正确率</text>
							<text class="stat-value">{{ getAccuracyRate(record) }}%</text>
						</view>
						<view class="stat-item">
							<text class="stat-label">用时</text>
							<text class="stat-value">{{ formatDuration(record.totalTime) }}</text>
						</view>
					</view>
					
					<view class="record-footer">
						<uv-icon name="arrow-right" size="16" color="#999"></uv-icon>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载更多 -->
		<view class="load-more-container" v-if="examRecords.length > 0">
			<uv-load-more 
				:status="loadMoreStatus"
				@loadmore="loadMore"
			></uv-load-more>
		</view>
	</view>
</template>

<script>
export default {
	name: 'ExamRecords',
	data() {
		return {
			// 搜索关键词
			searchKeyword: '',
			// 当前状态标签
			currentStatusTab: 0,
			// 状态标签列表
			statusTabs: [
				{ name: '全部' },
				{ name: '进行中' },
				{ name: '已完成' },
				{ name: '已评分' }
			],
			// 考试记录列表
			examRecords: [],
			// 加载状态
			loading: false,
			// 加载更多状态
			loadMoreStatus: 'loadmore',
			// 分页参数
			pageNum: 1,
			pageSize: 10,
			total: 0
		}
	},
	onLoad() {
		this.loadExamRecords();
	},
	onPullDownRefresh() {
		this.refreshData();
	},
	onReachBottom() {
		this.loadMore();
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack();
		},
		
		// 搜索处理
		handleSearch() {
			this.refreshData();
		},
		
		// 清空搜索
		handleClear() {
			this.searchKeyword = '';
			this.refreshData();
		},
		
		// 状态切换
		handleStatusChange(index) {
			this.currentStatusTab = index;
			this.refreshData();
		},
		
		// 刷新数据
		refreshData() {
			this.pageNum = 1;
			this.examRecords = [];
			this.loadExamRecords();
		},
		
		// 加载考试记录
		async loadExamRecords() {
			if (this.loading) return;
			
			this.loading = true;
			this.loadMoreStatus = 'loading';
			
			try {
				const params = {
					pageNum: this.pageNum,
					pageSize: this.pageSize
				};
				
				// 添加搜索条件
				if (this.searchKeyword) {
					params.searchKeyword = this.searchKeyword;
				}
				
				// 添加状态筛选
				if (this.currentStatusTab > 0) {
					const statusMap = ['', 'in_progress', 'completed', 'graded'];
					params.status = statusMap[this.currentStatusTab];
				}
				
				const res = await this.$api('getUserExamRecords', params);
				
				if (res.code === 200) {
					const newRecords = res.data.records || [];
					
					if (this.pageNum === 1) {
						this.examRecords = newRecords;
					} else {
						this.examRecords.push(...newRecords);
					}
					
					this.total = res.data.total || 0;
					
					// 更新加载更多状态
					if (this.examRecords.length >= this.total) {
						this.loadMoreStatus = 'nomore';
					} else {
						this.loadMoreStatus = 'loadmore';
					}
				} else {
					uni.showToast({
						title: res.msg || '加载失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载考试记录失败:', error);
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				});
			} finally {
				this.loading = false;
				uni.stopPullDownRefresh();
			}
		},
		
		// 加载更多
		loadMore() {
			if (this.loadMoreStatus === 'loadmore' && !this.loading) {
				this.pageNum++;
				this.loadExamRecords();
			}
		},
		
		// 查看记录详情
		viewRecordDetail(record) {
			uni.navigateTo({
				url: `/pages_order/exams/detail?userExamId=${record.userExamId}`
			});
		},
		
		// 获取状态样式类
		getStatusClass(status) {
			const classMap = {
				'not_started': 'status-not-started',
				'in_progress': 'status-in-progress',
				'completed': 'status-completed',
				'graded': 'status-graded'
			};
			return classMap[status] || 'status-default';
		},
		
		// 获取状态文本
		getStatusText(status) {
			const textMap = {
				'not_started': '未开始',
				'in_progress': '进行中',
				'completed': '已完成',
				'graded': '已评分'
			};
			return textMap[status] || '未知';
		},
		
		// 格式化时间
		formatTime(time) {
			if (!time) return '-';
			return this.$dayjs(time).format('YYYY-MM-DD HH:mm');
		},
		
		// 格式化时长
		formatDuration(seconds) {
			if (!seconds) return '0分钟';
			
			const hours = Math.floor(seconds / 3600);
			const minutes = Math.floor((seconds % 3600) / 60);
			
			if (hours > 0) {
				return `${hours}小时${minutes}分钟`;
			} else {
				return `${minutes}分钟`;
			}
		},
		
		// 计算正确率
		getAccuracyRate(record) {
			if (!record.totalQuestions || record.totalQuestions === 0) {
				return 0;
			}
			return Math.round((record.correctCount / record.totalQuestions) * 100);
		}
	}
}
</script>

<style lang="scss" scoped>
.exam-records-page {
	background-color: #f5f5f5;
	min-height: 100vh;
}

.search-filter-section {
	background-color: #fff;
	padding: 20rpx;
	margin-bottom: 20rpx;
	
	.search-box {
		margin-bottom: 20rpx;
	}
}

.records-list {
	padding: 0 20rpx;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
	
	.loading-text {
		margin-top: 20rpx;
		color: #999;
		font-size: 28rpx;
	}
}

.empty-container {
	padding: 100rpx 0;
}

.records-container {
	.record-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		position: relative;
		
		.record-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 20rpx;
			
			.exam-title {
				flex: 1;
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				line-height: 1.4;
				margin-right: 20rpx;
			}
			
			.status-badge {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 24rpx;
				color: #fff;
				white-space: nowrap;
				
				&.status-not-started {
					background-color: #909399;
				}
				
				&.status-in-progress {
					background-color: #E6A23C;
				}
				
				&.status-completed {
					background-color: #67C23A;
				}
				
				&.status-graded {
					background-color: #409EFF;
				}
				
				&.status-default {
					background-color: #909399;
				}
			}
		}
		
		.record-info {
			margin-bottom: 20rpx;
			
			.info-row {
				display: flex;
				margin-bottom: 10rpx;
				font-size: 28rpx;
				
				.label {
					color: #666;
					width: 160rpx;
				}
				
				.value {
					color: #333;
					flex: 1;
				}
			}
		}
		
		.record-stats {
			display: flex;
			justify-content: space-between;
			padding: 20rpx 0;
			border-top: 1rpx solid #f0f0f0;
			margin-bottom: 10rpx;
			
			.stat-item {
				text-align: center;
				flex: 1;
				
				.stat-label {
					display: block;
					font-size: 24rpx;
					color: #999;
					margin-bottom: 8rpx;
				}
				
				.stat-value {
					display: block;
					font-size: 28rpx;
					font-weight: 600;
					color: #333;
					
					&.score {
						color: #E6A23C;
					}
				}
			}
		}
		
		.record-footer {
			position: absolute;
			right: 30rpx;
			top: 50%;
			transform: translateY(-50%);
		}
	}
}

.load-more-container {
	padding: 20rpx;
}
</style>